import sqlite3
from fastapi import FastAPI, HTTPException, Depends
import uvicorn
from schemas import ItemCreate, ItemResponse
import database
from typing import List

app = FastAPI()

# 启动时初始化数据库


@app.on_event("startup")
def startup():
    database.init_db()

# 创建项目


@app.post("/items/", response_model=ItemResponse)
def create_item(item: ItemCreate, db=Depends(database.get_db)):
    try:
        cursor = db.execute(
            """
            INSERT INTO items (name, description, price, tax)
            VALUES (?, ?, ?, ?)
            """,
            (item.name, item.description, item.price, item.tax)
        )
        db.commit()

        # 获取刚插入的数据
        new_item = db.execute(
            "SELECT * FROM items WHERE id = ?",
            (cursor.lastrowid,)
        ).fetchone()

        return dict(new_item)

    except sqlite3.IntegrityError as e:
        raise HTTPException(400, f"Database error: {str(e)}")

# 获取所有项目


@app.get("/items/", response_model=List[ItemResponse])
def read_items(db=Depends(database.get_db)):
    items = db.execute("SELECT * FROM items").fetchall()
    return [dict(item) for item in items]

# 获取单个项目


@app.get("/items/{item_id}", response_model=ItemResponse)
def read_item(item_id: int, db=Depends(database.get_db)):
    item = db.execute(
        "SELECT * FROM items WHERE id = ?",
        (item_id,)
    ).fetchone()

    if not item:
        raise HTTPException(404, "Item not found")
    return dict(item)

# 更新项目


@app.put("/items/{item_id}", response_model=ItemResponse)
def update_item(item_id: int, item: ItemCreate, db=Depends(database.get_db)):
    db.execute(
        """
        UPDATE items SET
            name = ?,
            description = ?,
            price = ?,
            tax = ?
        WHERE id = ?
        """,
        (item.name, item.description, item.price, item.tax, item_id)
    )

    if db.total_changes == 0:
        raise HTTPException(404, "Item not found")

    db.commit()
    return read_item(item_id, db)

# 删除项目


@app.delete("/items/{item_id}")
def delete_item(item_id: int, db=Depends(database.get_db)):
    db.execute("DELETE FROM items WHERE id = ?", (item_id,))

    if db.total_changes == 0:
        raise HTTPException(404, "Item not found")

    db.commit()
    return {"message": "Item deleted"}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
